#include <stdio.h>
#include <string.h>


int main(int argc, char *argv[])
{
	int ret = 0;
	FILE *file;
	char buffer[256];
	char fields[8][3] = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid"};
	char checkFields[8] = {0, 0, 0, 0, 0, 0, 0, 0};
	int checkPassport = 1;
	int validPassport = 0;
	int error = 0;
	fpos_t position;

	printf("Day 4 ! \n");

	if (argc > 1)
		file = fopen(argv[1], "r");
	else
		file = fopen("input.txt", "r");
	
	if (file == NULL)
		return -1;
	
	while (!feof(file))
	{
		if (checkPassport == 0)
		{
			checkPassport = 1;
			fsetpos(file, &position);
		}

		fscanf(file, "%s", buffer);
		printf ("%s\n", buffer);
		//scan the information of buffer and check the occurence with valid passport
		for (int i = 0 ; i < 8 ; i++)
		{
	
			//Check if the field has already be control. if yes mean it is a new passport
			char *ret = strstr(buffer, fields[i]);
			printf ("buffer: %s, fields: %s - ret: %s\n", buffer, fields[i], ret);
			if (ret != NULL) 
			{
				
				printf("occurence %d char: %s\n", i, fields[i]);
				if (checkFields[i] == 0)
				{
					checkFields[i] = 1;
				}
				else
				{
					// Reset table. New passeport check
					printf ("error check field already check !\n");
					memset(checkFields, 0, sizeof(checkFields));
					fgetpos(file, &position);
					break;
				}
			}
			else
			{
				checkPassport = 0;
				error++;
				break;
			}
			checkPassport &= checkFields[i];

		}
		
		if (checkPassport)
			validPassport++;
	
		printf("Check passport: %d - valid passport: %d\n", checkPassport, validPassport);
	}

	fclose(file);


	return ret;
}


